//  Inside Microsoft Exchange 2007 Web Services 
//  Chapter 16
//
//  Copyright (c) 2007 David Sterling, Ben Spain, Mark Taylor, Huw Upshall, Michael Mainer.  
//  All rights reserved.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using ProxyHelpers.EWS;
using System.Diagnostics;

namespace FolderChangesExist
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeServiceBinding binding = new ExchangeServiceBinding();
            binding.Url = "https://yourServer/ews/Exchange.asmx";
            binding.Credentials = new NetworkCredential("username", "password", "domain");

            // TODO:  You must supply a valid SyncState value in your call to FolderChangesExist
            //
            //Console.WriteLine("Changes exist? " +
            //    FolderChangesExist(binding, yourSyncState));
        }

        /// <summary>
        /// Compares the passed in sync state with the current sync state on the server
        /// (Listing 16-6)
        /// </summary>
        /// <param name="binding">Binding to use for call</param>
        /// <param name="sinceSyncState">"lower" bounds of change</param>
        /// 
        static bool FolderChangesExist(ExchangeServiceBinding binding, string sinceSyncState)
        {
            SyncFolderHierarchyType request = new SyncFolderHierarchyType();
            request.FolderShape = new FolderResponseShapeType(DefaultShapeNamesType.IdOnly);
            request.SyncState = sinceSyncState;

            SyncFolderHierarchyResponseType response = binding.SyncFolderHierarchy(request);
            SyncFolderHierarchyResponseMessageType responseMessage =
                 response.ResponseMessages.Items[0] as SyncFolderHierarchyResponseMessageType;

            if (responseMessage.ResponseCode != ResponseCodeType.NoError)
            {
                throw new Exception("SyncFolderHierarchy failed with response code: " +
                      responseMessage.ResponseCode.ToString());
            }
            if (responseMessage.SyncState == sinceSyncState)
            {
                // If the sync state is the same, there are NO changes.  Assert this as 
                // EWS should be consistent.
                //
                Debug.Assert(responseMessage.Changes.Items == null);
                return false;
            }
            else
            {
                // If the sync state is different, then there should be changes.
                //
                Debug.Assert(responseMessage.Changes.Items != null);
                return true;
            }
        }

    }
}
